

package cn.shengchao.examstar.me.address.ohs.local.appservices;

import cn.shengchao.examstar.me.address.acl.ports.repositories.IAddressRepository;
import cn.shengchao.examstar.me.address.domain.Address;
import cn.shengchao.examstar.me.address.ohs.local.message.AddressDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressAppService {

    @Autowired
    private IAddressRepository iAddressRepository;

    public void saveAddress(AddressDto addressDto, Long userId) {
        Address address = new Address();
        address.setId(addressDto.getId());
        address.setProvince(addressDto.getProvince());
        address.setCity(addressDto.getCity());
        address.setCounty(addressDto.getCounty());
        address.setDetail(addressDto.getDetail());
        address.setUserId(userId);
        address.setDefaultAddress(addressDto.getDefaultAddress());
        address = iAddressRepository.save(address);
        setDefaultAddress(userId, address.getId(), addressDto.getDefaultAddress());
    }

    private void setDefaultAddress(Long userId, Long id, Boolean defaultAddress) {
        List<Address> address = iAddressRepository.getList(userId);
        if (address.size() == 1) {
            iAddressRepository.updateDefaultAddress(address.getFirst(), true);
        }
        if (defaultAddress) {
            address.forEach(a -> {
                // 如果当前地址是默认地址,并且未设置成默认地址
                if (a.getId().equals(id) && !a.getDefaultAddress()) {
                    iAddressRepository.updateDefaultAddress(a, true);
                }
                if (!a.getId().equals(id) && a.getDefaultAddress()) {
                    iAddressRepository.updateDefaultAddress(a, false);
                }
            });
        }
    }

    public List<AddressDto> getList(Long uid) {
        return iAddressRepository.getList(uid).stream().map(item -> {
            AddressDto addressDto = new AddressDto();
            addressDto.setId(item.getId());
            addressDto.setProvince(item.getProvince());
            addressDto.setCity(item.getCity());
            addressDto.setCounty(item.getCounty());
            addressDto.setDetail(item.getDetail());
            addressDto.setDefaultAddress(item.getDefaultAddress());
            return addressDto;
        }).toList();
    }

    public AddressDto defaultAddress(Long uid) {
        return this.getList(uid).stream().filter(AddressDto::getDefaultAddress).findFirst().orElse(new AddressDto());
    }
}
